import { defineStore } from "pinia"
import { ref } from 'vue'
import { fieldAuthsApi } from '@/api'

type FieldAuth = {value: string, label: string}

export default defineStore('useFieldAuth', () => {
  const data = ref<FieldAuth[]>()

  async function getData() {
    if(!data.value) {
      data.value = []
      const res = await fieldAuthsApi()
      for(const value in res.data) {
        data.value.push({value, label: res.data[value]})
      }
    }

    return data.value
  }

  async function search(queryString?: string) {
    const ret: FieldAuth[] = []

    const datalist = await getData()
    if(!queryString || !queryString.startsWith('=')) {
      for(const item of datalist) ret.push(item)
    } else {
      for(const item of datalist) {
        if(item.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0) {
          ret.push(item)
        }
      }
    }

    return ret
  }

  return { search }
}, { persist: false })
